package com.tms.springboot.controller;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageInfo;
import com.tms.springboot.aggregation.pojo.*;
import com.tms.springboot.result.JsonResult;
import com.tms.springboot.result.ResultTool;
import com.tms.springboot.search.TransportSearch;
import com.tms.springboot.service.*;
import com.tms.springboot.utils.UUId;
import com.tms.springboot.view.DriverMian;
import com.tms.springboot.view.PageVo;
import com.tms.springboot.view.TransportPassage;
import com.tms.springboot.view.TransportView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author cjj
 * @since 2023-06-14
 */
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/pd-auth-user")
public class PdAuthUserController {

    @Autowired
    PdAuthUserService pdAuthUserService;
    @Autowired
    PdCoreStationService pdCoreStationService;//岗位

    @Autowired
    PdDriverJobService pdDriverJobService;

    @Autowired
    PdTaskTransportService pdTaskTransportService;

    @Autowired
    PdTransportOrderTaskService pdTransportOrderTaskService;

    @Autowired
    PdOrderService pdOrderService;

    @Autowired
    PdTransportOrderService pdTransportOrderService;

    @Autowired
    PdCoreOrgService pdCoreOrgService;

    @Autowired
    PdTaskPickupDispatchService pdTaskPickupDispatchService;


    //快递员管理分页查询
    @RequestMapping("/pdauthuserpagequery")
    public JsonResult pdauthuserpagequery(@RequestBody PageVo<PdAuthUser> pageVo) {
        PageInfo pageInfo = pdAuthUserService.pdauthuserpagequerylk(pageVo);
        return pageInfo != null ? ResultTool.success(pageInfo) : ResultTool.fail();
    }

    //删除快递员,将快递员角色改为null
    @GetMapping("/delkdy")
    public JsonResult delkdy(String id) {
        UpdateWrapper wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id);
        wrapper.set("station_id", null);
        Boolean update = pdAuthUserService.update(wrapper);
        return ResultTool.success(update);
    }

    //查询没有角色的账号
    @RequestMapping("/querynotrole")
    public JsonResult querynotrole() {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.isNull("station_id");
        wrapper.eq("status", 1);
        List<PdAuthUser> pdAuthUserList = pdAuthUserService.list(wrapper);
        return pdAuthUserList != null ? ResultTool.success(pdAuthUserList) : ResultTool.fail();
    }

    //添加快递员,给账号加上快递员角色
    @GetMapping("/addrole")
    public JsonResult addrole(String id) {
        //查询快递员岗位id
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", "快递员");
        PdCoreStation pdCoreStation = pdCoreStationService.getOne(queryWrapper);
        //添加快递员角色
        UpdateWrapper wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id);
        wrapper.set("station_id", pdCoreStation.getId());
        Boolean update = pdAuthUserService.update(wrapper);
        return ResultTool.success(update);
    }

    //修改快递员信息
    @RequestMapping("/updatekdy")
    public JsonResult updatekdy(@RequestBody PdAuthUser pdAuthUser) {
        Boolean update = pdAuthUserService.updateById(pdAuthUser);
        return ResultTool.success(update);
    }

    /**
     * 司机端登录
     *
     * @param pdAuthUser
     * @return
     */
    @RequestMapping("/loginDriver")
    public PdAuthUser loginDriver(@RequestBody PdAuthUser pdAuthUser) {

        PdAuthUser one = this.pdAuthUserService.getOne(new QueryWrapper<PdAuthUser>()
                .eq("account", pdAuthUser.getAccount())
                .eq("password", pdAuthUser.getPassword())
                .eq("station_id", 2)
                .eq("status", true));

        return one;
    }

    /**
     * 查询司机端个人信息
     *
     * @param pdAuthUser
     * @return
     * @throws Exception
     */
    @RequestMapping("/selectMain")
    public DriverMian selectMain(@RequestBody PdAuthUser pdAuthUser) throws Exception {

        DriverMian driverMian = this.pdAuthUserService.selectMainService(pdAuthUser.getId());

        return driverMian;

    }

    /**
     * 查询历史记录
     *
     * @param transportSearch
     * @return
     * @throws Exception
     */
    @RequestMapping("/selectHistory")
    public List<PdTaskTransport> selectHistory(@RequestBody TransportSearch transportSearch) throws Exception {

        List<PdTaskTransport> pdTaskTransports = this.pdAuthUserService.selectHistoryService(transportSearch);

        return pdTaskTransports;

    }

    /**
     * 根据运输任务编号查询运输任务详细信息
     *
     * @param transportSearch
     * @return
     */
    @RequestMapping("/transportfindById")
    public TransportView transportfindById(@RequestBody TransportSearch transportSearch) throws Exception {

        TransportView transportView = this.pdAuthUserService.transportfindByIdService(transportSearch.getTransportId());

        System.out.println(transportView);

        return transportView;

    }

    /**
     * 查询可以货物的提货
     *
     * @param pdAuthUser
     * @return
     */
    @RequestMapping("/selectDrverJobStatus")
    public List<PdDriverJob> selectDrverJobStatus(@RequestBody PdAuthUser pdAuthUser) throws Exception {

        List<PdDriverJob> pdDriverJobs = this.pdAuthUserService.selectDrverJobStatusService(pdAuthUser.getId());

        return pdDriverJobs;

    }

    /**
     * 司机提货
     *
     * @param transportView
     * @return
     */
    @RequestMapping("/drverJobStatus")
    public boolean drverJobStatus(@RequestBody TransportView transportView) {

        List idone = new ArrayList<>();

        List idtwo = new ArrayList<>();

        //司机作业单已提货
        boolean update = this.pdDriverJobService.update(new UpdateWrapper<PdDriverJob>().eq("task_transport_id", transportView.getId())
                .set("start_handover", transportView.getStartHandover())
                .set("status", 2)
                .set("actual_departure_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));

        if (update) {

            //运输任务表已提货
            boolean update1 = this.pdTaskTransportService.update(new UpdateWrapper<PdTaskTransport>().eq("id", transportView.getId())
                    .set("status", 2)
                    .set("actual_pick_up_goods_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                    .set("cargo_pick_up_picture", transportView.getCargoPickUpPicture())
                    .set("cargo_picture", transportView.getCargoPicture())
                    .set("actual_departure_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));

            if (update1) {

                List<PdTransportOrderTask> transport_task_id = this.pdTransportOrderTaskService.list(new QueryWrapper<PdTransportOrderTask>().eq("transport_task_id", transportView.getId()));

                for (PdTransportOrderTask pdTransportOrderTask : transport_task_id) {

                    //运单表提货
                    boolean update2 = this.pdTransportOrderService.update(new UpdateWrapper<PdTransportOrder>().eq("id", pdTransportOrderTask.getTransportOrderId())
                            .set("status", 2));

                    idone.add(update2);

                    //根据运单编号查询订单信息
                    PdTransportOrder byId = this.pdTransportOrderService.getById(pdTransportOrderTask.getTransportOrderId());

                    //订单表提货
                    boolean update3 = this.pdOrderService.update(new UpdateWrapper<PdOrder>().eq("id", byId.getOrderId())
                            .set("status", 5));

                    idtwo.add(update3);

                }

                if (idone.contains(false) && idtwo.contains(false)) {

                    return false;

                } else {

                    return true;

                }

            }

        }

        return false;

    }

    /**
     * 查询司机在途
     *
     * @param pdAuthUser
     * @return
     * @throws Exception
     */
    @RequestMapping("/selectPassage")
    public TransportPassage selectPassage(@RequestBody PdAuthUser pdAuthUser) throws Exception {

        TransportPassage transportPassage = this.pdAuthUserService.selectPassageService(pdAuthUser.getId());

        return transportPassage;

    }

    /**
     * 查询司机作业单为运输中
     *
     * @param pdAuthUser
     * @return
     * @throws Exception
     */
    @RequestMapping("/selectDelivery")
    public List<PdDriverJob> selectDelivery(@RequestBody PdAuthUser pdAuthUser) throws Exception {

        List<PdDriverJob> pdDriverJobs = this.pdAuthUserService.selectDeliveryService(pdAuthUser.getId());

        return pdDriverJobs;

    }

    /**
     * 图片上传
     *
     * @param myfile
     * @return
     */
    @RequestMapping("/uploadcontroller")
    public String uploadcontroller(@RequestBody() MultipartFile myfile) {
// Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tMub75G3BEbTGuuppxj";
        String accessKeySecret = "45TZy8Cjt5VGIqSEmDiEKijJ5JF1Ao";
// 填写Bucket名称，例如examplebucket。
        String bucketName = "czgnb";
//你上传到oss后的名字 会根据日期帮你创建文件夹。
        String objectName = String.valueOf(UUID.randomUUID());
        String hz = myfile.getOriginalFilename().substring(myfile.getOriginalFilename().indexOf(".") + 1);
// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream = myfile.getInputStream();
// 创建PutObject请求。
            ossClient.putObject(bucketName, objectName + "." + hz, inputStream);
        } catch (Exception oe) {

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        // https://czgnb.oss-cn-hangzhou.aliyuncs.com
        String url = "https://" + bucketName + "." + endpoint + "/" + objectName + "." + hz;
        String s = JSON.toJSONString(url);
        return s;
    }

    /**
     * 司机交付
     *
     * @param transportView
     * @return
     */
    @RequestMapping("/deliveryTransport")
    public boolean deliveryTransport(@RequestBody TransportView transportView) {

        List idone = new ArrayList<>();

        List idtwo = new ArrayList<>();

        List idthree = new ArrayList<>();

        //司机作业单表交付
        boolean update = this.pdDriverJobService.update(new UpdateWrapper<PdDriverJob>().eq("task_transport_id", transportView.getId())
                .set("status", 3)
                .set("finish_handover", transportView.getFinishHandover())
                .set("actual_arrival_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));

        //根据编号查询司机作业单信息
        PdDriverJob byId1 = this.pdDriverJobService.getById(transportView.getId());

        PdCoreOrg byId2 = this.pdCoreOrgService.getById(byId1.getEndAgencyId());

        if (update) {

            boolean update1 = this.pdTaskTransportService.update(new UpdateWrapper<PdTaskTransport>().eq("id", transportView.getId())
                    .set("status", 4)
                    .set("transport_certificate", transportView.getTransportCertificate())
                    .set("deliver_picture", transportView.getDeliverPicture())
                    .set("actual_arrival_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                    .set("actual_delivery_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));

            if (update1) {

                //根据任务运输编号查询运单与运输任务关联表
                List<PdTransportOrderTask> transport_task_id = this.pdTransportOrderTaskService.list(new QueryWrapper<PdTransportOrderTask>().eq("transport_task_id", transportView.getId()));

                for (PdTransportOrderTask pdTransportOrderTask : transport_task_id) {

                    //运单表交付
                    boolean update2 = this.pdTransportOrderService.update(new UpdateWrapper<PdTransportOrder>().eq("id", pdTransportOrderTask.getTransportOrderId())
                            .set("status", 4));

                    idone.add(update2);

                    //根据运单编号查询订单信息
                    PdTransportOrder byId = this.pdTransportOrderService.getById(pdTransportOrderTask.getTransportOrderId());

                    //订单表交付
                    boolean update3 = this.pdOrderService.update(new UpdateWrapper<PdOrder>().eq("id", byId.getOrderId())
                            .set("status", 6));

                    idtwo.add(update3);

                    if (byId2.getOrgType() == 4) {

                        PdTaskPickupDispatch pdTaskPickupDispatch = new PdTaskPickupDispatch();
                        pdTaskPickupDispatch.setId(UUId.nextId());
                        pdTaskPickupDispatch.setOrderId(byId.getOrderId());
                        pdTaskPickupDispatch.setTaskType(2);
                        pdTaskPickupDispatch.setStatus(1);
                        pdTaskPickupDispatch.setAgencyId(byId2.getId());
                        pdTaskPickupDispatch.setCreateTime(LocalDateTime.now());

                        boolean save = this.pdTaskPickupDispatchService.save(pdTaskPickupDispatch);

                        idthree.add(save);

                    }

                }

                if (idthree != null) {

                    if (idone.contains(false) && idtwo.contains(false) && idthree.contains(false)) {

                        return false;

                    } else {

                        return true;

                    }

                } else {

                    if (idone.contains(false) && idtwo.contains(false)){

                        return false;

                    }else{

                        return true;

                    }

                }

            }

        }

        return false;

    }
}
